package org.duncan.sjge.keyboard;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Duncan
 */
public class Keyboard {
    private Map<Integer, Boolean> mKeyStatus = new HashMap<>();
    private Map<String, Integer> mKeyMap     = new HashMap<>();
    
    private Keyboard() {}
    
    public KeyListener createListener() {
        return new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent ke) {
                mKeyStatus.put(ke.getKeyCode(), Boolean.TRUE);
            }

            @Override
            public void keyReleased(KeyEvent ke) {
                mKeyStatus.put(ke.getKeyCode(), Boolean.FALSE);
            }
        };
    }
    
    public void addMapping(final String id, int key) {
        mKeyMap.put(id, key);
    }
    
    public boolean isPressed(final String id) {
        if (!mKeyMap.containsKey(id)) {
            System.err.println("Error! Unknown keymap: '" + id + "'.");
            System.exit(1);
        }
        return isPressed(mKeyMap.get(id));
    }
    
    public boolean isPressed(final int key) {
        if (mKeyStatus.get(key) == null) {
            return false;
        } else {
            return mKeyStatus.get(key).booleanValue();
        }
    }
    
    
    private static Keyboard inst;
    public static Keyboard instance() {
        if (inst == null) inst = new Keyboard();
        return inst;
    }
}
